<?php
/** Copyright 2014 TinPhp Systems, Inc.
 * @author zhangxilian 2013-8-20
 * @package TinPhp
 */
if (!defined('IN_TINPHP')) {
	exit ('Access Denied');
}

require_once(TIN_APP_PATH . 'include/adodb5/adodb.inc.php');
require_once(TIN_APP_PATH . 'include/adodb5/adodb-exceptions.inc.php');
require_once(TIN_APP_PATH . 'configs/db.conf.php');
/** 创建数据库链接工厂类 */
class DBFactory {
	
	private static $_dbconn;
	private static $_instance;
	
	public function __construct(){ }
	
	/** 阻止用户复制对象实例 */
	public function __clone(){
		trigger_error('Clone is not allow',E_USER_ERROR);
	}	
	/** 单例获取链接对象方法 */
	public static function getInstance(){
		if(!isset(self::$_instance)){
			$c = __CLASS__;
			self::$_instance = new $c;
		}
		return self::$_instance;
	}
	/** 获取数据链接对象 
     * @param string $dbType 数据库类型，指定创建的DAO类
     */
	public static function getDBConn($dbType = TIN_DB_TYPE){
		if(!isset(self::$_dbconn[$dbType])){
			self::$_dbconn[$dbType] = self::createDBConn($dbType);			
		}
		return self::$_dbconn[$dbType];
	}
	/** 关闭所有数据链接 */
	public static function closeDBConn(){
		if(isset(self::$_dbconn)){
			foreach(self::$_dbconn as $k=>$v){
				$v->Disconnect();
			}
		}
	}
	/** 创建数据库链接对象 
     * @param string $dbTypeKey 数据库类型，指定创建的DAO类
     */
	private static function createDBConn($dbTypeKey = TIN_DB_TYPE) {
		//echo "<hr>Create new dbconn $dbTypeKey<hr>";
		$dbParams = $GLOBALS['TIN_DB_CONN'][$dbTypeKey];
		$dbType = $dbParams['dbtype'];
		if (empty($dbType)){
			$dbType = "mysql";
		}
		$db = &NewADOConnection($dbType);
		if (!$db or empty($db)) 
			die("Error when connecting to database： <u>" . $db->ErrorMsg() . "</u>");
		try{
			//兼容
//			$connected = $db->Connect($dbParams['dbhost'], $dbParams['dbuser'],
//						 $dbParams['dbpass'], $dbParams['dbname']);
//			//其他数据库
			$connected = $db->PConnect($dbParams['dbhost'], $dbParams['dbuser'],
										$dbParams['dbpass'], $dbParams['dbname']);
//			//Oracle
//			$connected = $db->NConnect($dbParams['dbhost'], $dbParams['dbuser'],
//										$dbParams['dbpass'], $dbParams['dbname']);
		}catch(Exception $e){
			//echo "".$e->getMessage();
		}
		
		if (!$connected or empty($connected))
			die("Error when connecting to database : <u>" . $db->ErrorMsg() . "</u>");
		//$db->debug = true;
		if($dbType=="mysql" || $dbType=="mysqlt")
			$db->Execute("set names '".$dbParams['dbcharset']."'");
		
		return $db;
  }
	
}//End Class
?>
